package com.mayikt.main.callback;


import com.mayikt.common.core.utils.DesensitizationUtil;
import com.mayikt.main.api.impl.entity.SysUser;
import com.mayikt.main.api.impl.entity.SysUserLoginLog;
import com.mayikt.main.container.AsyncLogWrappper;
import com.mayikt.main.container.MayiktLogContainer;
import com.mayikt.main.manage.LoginLogManage;
import com.mayikt.main.manage.WechatTemplateManage;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * @author wangjin
 * @title: ApplicatiponRunnerImpl
 * @projectName mayikt-cloud
 * @description: TODO
 * @date 2022/5/2 0002 14:21
 */
@Component
@Slf4j
public class ApplicatiponRunnerImpl implements ApplicationRunner {
    @Value("${mayikt.log.threads}")
    private Integer mayiktLogThreads;
    @Value("${mayikt.log.threadName}")
    private String threadName;
    @Autowired
    private LoginLogManage loginLogManage;
    @Autowired
    private WechatTemplateManage wechatTemplateManage;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("<springboot启动成功。。。。。>");
        initLogThread();
    }

    private void initLogThread() {
        for (int i = 0; i < mayiktLogThreads; i++) {
            //指定线程名称
            new Thread(new LogThread(), threadName).start();
        }
    }

    /**
     * @Author wangjin
     * @Description //从队列中取出 登录后续流程包装对象操作
     * @Date 2022/5/2 0002
     * @Param * @param null:
     * @return * @return: null
     **/

    class LogThread implements Runnable {
        @SneakyThrows
        @Override
        public void run() {
            while (true) {
                AsyncLogWrappper asyncLogWrappper = MayiktLogContainer.getlinkedBlockingQueue().poll();
                if (asyncLogWrappper != null) {
                    SysUserLoginLog sysUserLoginLog = asyncLogWrappper.getSysUserLoginLog();
                    //登录后续流程
                    loginLogManage.asynLoginLog(sysUserLoginLog);
                    //微信登录提醒
                    SysUser sysUser = asyncLogWrappper.getSysUser();
                    wechatTemplateManage.sendLoginTemplate("ommED6cuwHYsgnT5WcamQhf2zJio", DesensitizationUtil.mobileEncrypt(sysUser.getPhoneNumber()), sysUserLoginLog.getLoginTime(), sysUserLoginLog.getLoginIp(), sysUserLoginLog.getEquipment());
                }
                //为了避免空转问题，导致cpu标高
                Thread.sleep(30);
            }

        }
    }
}
